package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.atguigu.gmall.rebbit.constant.MqConst;
import com.atguigu.gmall.rebbit.service.RabbitService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class ManageServiceImpl implements ManageService {
    @Autowired
    private GetCertgory1Mapper getCertgoryMapper;

    @Autowired
    private GetCertgory2Mapper getCertgory2Mapper;

    @Autowired
    private GetCertgory3Mapper getCertgory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;

    @Autowired
    private SkuInfoMapper skuInfoMapper;

    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SpuImageMapper spuImageMapper;

    @Autowired
    private SpuInfoMapper spuinfoMapper;

    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Autowired
    private SkuImageMapper skuImageMapper;

    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;

    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    private BaseCategoryViewBaseCategoryViewMapper baseCategoryViewBaseCategoryViewMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RabbitService rabbitService;

    //根据平台id获取平台属性
    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        List<BaseAttrInfo> list = baseAttrInfoMapper.getBaseAttrInfo(category1Id, category2Id, category3Id);
        return list;
    }


    //获取一级id
    @Override
    public List<BaseCategory1> getCategory1() {
        List<BaseCategory1> list = getCertgoryMapper.selectList(null);
        return list;
    }


    //获取二级id
    @Override
    public List<BaseCategory2> getCategoty2(Long category1Id) {
        List<BaseCategory2> list = getCertgory2Mapper.selectList(new QueryWrapper<BaseCategory2>()
                .eq("category1_id", category1Id));
        return list;
    }


    //获取三级id
    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        List<BaseCategory3> list = getCertgory3Mapper.selectList(new QueryWrapper<BaseCategory3>()
                .eq("category2_id", category2Id));
        return list;

    }

    //添加平台属性
    @Transactional//事务
    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if (baseAttrInfo.getId() != null) {
            System.out.println(111111);
            QueryWrapper<BaseAttrValue> wrapper = new QueryWrapper<>();
            wrapper.eq("attr_id", baseAttrInfo.getId());
            List<BaseAttrValue> baseAttrValues = baseAttrValueMapper.selectList(wrapper);
            baseAttrValues.forEach(baseAttrValue -> {
                baseAttrValueMapper.deleteById(baseAttrValue);
            });
            attrValueList.forEach(attrValue -> {
                attrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(attrValue);
            });
            Integer integer = baseAttrValueMapper.selectCount(wrapper);
            if (integer == 0) {
                baseAttrInfoMapper.deleteById(baseAttrInfo);
            }
            return;
        }
        baseAttrInfoMapper.insert(baseAttrInfo);

        attrValueList.forEach(attrValue -> {
            attrValue.setAttrId(baseAttrInfo.getId());
            baseAttrValueMapper.insert(attrValue);
        });
    }

    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        QueryWrapper<BaseAttrValue> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_id", attrId);
        List<BaseAttrValue> baseAttrValues = baseAttrValueMapper.selectList(wrapper);
        return baseAttrValues;
    }

    @Override
    public IPage baseTrademark(Integer page, Integer limit) {
        Page<BaseTrademark> page1 = new Page<>(page, limit);
        IPage<BaseTrademark> iPage = baseTrademarkMapper.selectPage(page1, null);
        return iPage;
    }

    @Override
    public void baseTrademarkRemove(Long id) {
        baseTrademarkMapper.deleteById(id);
    }

    //修改品牌回显
    @Override
    public BaseTrademark baseTrademarkGet(Long id) {
        BaseTrademark baseTrademark = baseTrademarkMapper.selectById(id);
        return baseTrademark;
    }

    //修改品牌列表
    @Override
    public void baseTrademarkUpdate(BaseTrademark baseTrademark) {
        baseTrademarkMapper.updateById(baseTrademark);
    }

    //获取SPU列表信息
    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        List<BaseSaleAttr> list = baseSaleAttrMapper.selectList(null);
        return list;
    }

    //获取SKU列表
    @Override
    public IPage SKUList(Integer page, Integer limit) {
        return skuInfoMapper.selectPage(new Page<>(page, limit), null);
    }

    //添加品牌列表
    @Override
    public void baseTrademarkSave(BaseTrademark baseTrademark) {
        baseTrademarkMapper.insert(baseTrademark);
    }

    //获取SPU列表
    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long id) {
        List<SpuSaleAttr> list = spuSaleAttrMapper.spuSaleAttrList(id);
        return list;
    }

    //获取SPU图片
    @Override
    public List<SpuImage> spuImageList(Long spuId) {
        List<SpuImage> list = spuImageMapper.selectList(new QueryWrapper<SpuImage>()
                .eq("spu_id", spuId));
        return list;
    }

    //上架
    @Override
    public void onSale(Long id) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(id);
        skuInfo.setIsSale(SkuInfo.SALE);
        skuInfoMapper.updateById(skuInfo);
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_UPPER,id);
    }

    //下架
    @Override
    public void cancelSale(Long id) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(id);
        skuInfo.setIsSale(SkuInfo.NOSALE);
        skuInfoMapper.updateById(skuInfo);
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_LOWER,id);
    }


    //添加SPU
    @Transactional
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        spuinfoMapper.insert(spuInfo);
        Long id = spuInfo.getId();
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        spuImageList.forEach(spuImage -> {
            spuImage.setSpuId(spuInfo.getId());
            spuImageMapper.insert(spuImage);
        });
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        spuSaleAttrList.forEach(spuSaleAttr -> {
            spuSaleAttr.setSpuId(spuInfo.getId());
            spuSaleAttrMapper.insert(spuSaleAttr);
            List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
            spuSaleAttrValueList.forEach(spuSaleAttrValue -> {
                spuSaleAttrValue.setSpuId(spuInfo.getId());
                spuSaleAttrValue.setBaseSaleAttrId(spuSaleAttr.getId());
                spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                spuSaleAttrValueMapper.insert(spuSaleAttrValue);
            });
        });
    }


    //添加SKU
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        skuInfoMapper.insert(skuInfo);
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        skuImageList.forEach(skuImage -> {
            skuImage.setSkuId(skuInfo.getId());
            skuImageMapper.insert(skuImage);
        });
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        skuAttrValueList.forEach(skuAttrValue -> {
            skuAttrValue.setSkuId(skuInfo.getId());
            skuAttrValueMapper.insert(skuAttrValue);
        });
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
            skuSaleAttrValue.setSkuId(skuInfo.getId());
            skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            skuSaleAttrValueMapper.insert(skuSaleAttrValue);
        });
    }

    //查询一二三级分类
    @Override
    @GmallCache(prefix = "getBaseCategoryView")
    public BaseCategoryView getBaseCategoryView(Long category3Id) {
        BaseCategoryView view = baseCategoryViewBaseCategoryViewMapper.selectOne(new QueryWrapper<BaseCategoryView>()
                .eq("category3_id", category3Id));

        return view;
    }

    //查询Sku中的信息及图片
    @Override
    @GmallCache(prefix = "getSkuInfo")
    public SkuInfo getSkuInfo(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if(skuInfo==null){
            return new SkuInfo();
        }
        List<SkuImage> skuimageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId));
        skuInfo.setSkuImageList(skuimageList);
        return skuInfo;
    }

    //获取商品价格
    @Override
    public BigDecimal getSkuPrice(Long skuId) {
        return skuInfoMapper.getSkuPrice(skuId);
    }

    //查询spu中总销售属性及属性值，默认一个商品
    @Override
    @GmallCache(prefix = "getSpuSaleAttrListCheckBySku")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
        List<SpuSaleAttr> checkBySku = spuSaleAttrMapper.getSpuSaleAttrListCheckBySku(skuId, spuId);
        return checkBySku;
    }

    //查询页面上的组合与skuId之间的关系")//{1|2|3,1|3|4}json格式的字符串
    @Override
    @GmallCache(prefix = "getSkuValueIdsMap")
    public Map getSkuValueIdsMap(Long spuId) {
        Map<String, String> hashMap = new HashMap<>();
        List<Map> listMap = spuSaleAttrValueMapper.getSkuValueIdsMap(spuId);
        listMap.forEach(map -> {
            hashMap.put(String.valueOf(map.get("value_id")), String.valueOf(map.get("sku_id")));
        });
        return hashMap;
    }

    //获取所有的一级二级三级分类
    @Override
    public List<BaseCategoryView> getBaseCategoryViewList() {
        return baseCategoryViewBaseCategoryViewMapper.selectList(null);
    }

    //获取品牌
    @Override
    public BaseTrademark getBaseTrademark(Long tmId) {
        return baseTrademarkMapper.selectById(tmId);
    }

    //总和表
    @Override
    public List<SkuAttrValue> getSkuAttrValue(Long skuId) {
        return skuAttrValueMapper.getSkuAttrValue(skuId);
    }
}
